package quickcore.webview;

import android.Manifest;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class WebViewFragment extends PermissionSupport implements WebViewListener, PermissionsContract.PermissionListener{
    private WebView webView;
    private boolean isOther;
    private boolean isOpen;
    private ValueCallback<Uri> valueCallback;
    private ValueCallback<Uri[]> valueCallback2;
    private String callUrl;
    //弹窗
    private AlertDialog alertDialog;
    private boolean isViewInit;
    private WebViewListener.TitleListener titleListener;
    public WebViewFragment(){}
    public static WebViewFragment newInstance(String url){
        WebViewFragment f = new WebViewFragment();
        Bundle b = new Bundle();
        b.putString("loadUrl",url);
        f.setArguments(b);
        return f;
    }
    public static WebViewFragment newInstance(){
        WebViewFragment f = new WebViewFragment();
        return f;
    }

    @Override
    public void onPermissionsGranted(int requestCode) {
        if (alertDialog.isShowing()) {
            alertDialog.dismiss();
        }
        switch (requestCode) {
            case 1:
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);//调用android的相机
                startActivityForResult(intent, 1);
                break;
            case 2:
                callPhone(callUrl);
                break;
        }
    }
    public void setTitleListener(TitleListener titleListener){
        this.titleListener = titleListener;
    }
    @Override
    public void onPermissionsDenied(int requestCode) {
        if (alertDialog.isShowing()) {
            alertDialog.dismiss();
        }
        //从相机或相册取出照片后如果重新选择需要制空变量
        if (valueCallback2 != null) {
            valueCallback2.onReceiveValue(null);
            valueCallback2 = null;
        }
        if (valueCallback != null) {
            valueCallback.onReceiveValue(null);
            valueCallback = null;
        }
        switch (requestCode) {
            case 1:
                Toast.makeText(getContext(), "您拒绝了打开相机权限", Toast.LENGTH_SHORT).show();
                break;
            case 2:

                break;
        }
    }


    private class ReOnCancelListener implements DialogInterface.OnCancelListener {

        @Override
        public void onCancel(DialogInterface dialogInterface) {
            if (valueCallback != null) {
                valueCallback.onReceiveValue(null);
                valueCallback = null;
            }
            if (valueCallback2 != null) {
                valueCallback2.onReceiveValue(null);
                valueCallback2 = null;
            }
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (webView != null) {
            webView.destroy();
        }
        webView = new WebView(getContext());
        isViewInit = true;
        return webView;

    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        String dir = getContext().getDir("database", Context.MODE_PRIVATE).getPath();
        WebViewSetup.builder()
                .setWebViewClient(this)
                .setLocationDbPath(dir)
                .setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK)
                .build().setupWebView(webView);
        creatOptions();
        Bundle bundle = getArguments();
        if(bundle!=null){
            String url =  bundle.getString("loadUrl","");
            webView.loadUrl(url);
        }
    }


    public void creatOptions() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setOnCancelListener(new ReOnCancelListener());
        builder.setTitle("选择");
//        builder.setCancelable(false);
        builder.setItems(new String[]{
                        "相机",
                        "相册"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {

                            /**
                             * 开始申请调用相机需要的权限
                             */
                            doRequestPermissions(new String[]{Manifest.permission.CAMERA}, 1, WebViewFragment.this);

                        } else {
                            Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);//调用android的图库
                            startActivityForResult(i, 2);
                        }
                    }
                }
        );
        alertDialog = builder.create();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (data != null) {
                Uri uri = data.getData();
                if (uri == null) {
                    Bitmap bitmap = (Bitmap) data.getExtras().get("data");
                    uri = Uri.parse(MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), bitmap, null, null));
                }
                if (valueCallback2 != null && uri != null) {
                    Uri[] uris = new Uri[]{uri};
                    valueCallback2.onReceiveValue(uris);
                    valueCallback2 = null;
                } else if (valueCallback != null && uri != null) {
                    valueCallback.onReceiveValue(uri);
                    valueCallback = null;
                }
            }
        }
    }

    @Override
    public void onResume() {
        webView.onResume();
        super.onResume();
        isOpen = false;
        //从相机或相册取出照片后如果重新选择需要制空变量
        if (Build.VERSION.SDK_INT >= 21) {
            if (valueCallback2 != null) {
                valueCallback2.onReceiveValue(null);
                valueCallback2 = null;
            }
            return;
        }

        if (valueCallback != null) {
            valueCallback.onReceiveValue(null);
            valueCallback = null;
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        webView.onPause();
    }

    @Override
    public void onDestroyView() {
        isViewInit = false;
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if(webView!=null){
            webView.destroy();
            webView = null;
        }
    }

    @Override
    public void setTitleView(String title) {
        titleListener.onLoadTitle(title);
    }
    @Override
    public void loadUrl(WebView webView, boolean isWebScheme, String scheme, String url) {
        if(!isWebScheme){
            isOther = true;
            Uri uri = Uri.parse(url);
            try {
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                //跳转指定协议打开外部应用
                startActivity(intent);
                isOpen = true;
            } catch (ActivityNotFoundException exception) {
                //这个时候可以理解为用户没有安装指定的应用
                isOpen = false;
            }
        }else{
            isOther = false;
            webView.loadUrl(url);
        }
    }
    @Override
    public void onDownload(String url) {
        if(isOther&&!isOpen){
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }else if(!isOther && !isOpen){
            //普通协议，调用系统浏览器下载
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }
    }
    private void callPhone(String url) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
        startActivity(intent);
    }
    @Override
    public void onOpenFile(boolean is, ValueCallback<Uri[]> callback, ValueCallback<Uri> callback2) {
        if(is){
            this.valueCallback2 = callback;
        }else{
            this.valueCallback = callback2;
        }
        alertDialog.show();
    }
    public WebView getWebView(){
        return isViewInit?webView:null;
    }
}
